package zsc.liangyi.blog.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zsc.liangyi.blog.dao.UserDao;
import zsc.liangyi.blog.model.domain.Authority;
import zsc.liangyi.blog.model.domain.User;
import zsc.liangyi.blog.service.UserService;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
@CacheConfig(cacheNames = "user")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Resource
    private RedisTemplate<String ,Object> redisTemplate;

    @Override
    public User selectUserWithId(Integer id) {
        log.info("作者id："+id);
        Object o=redisTemplate.opsForValue().get("user_"+id);
        if(o!=null){
            return (User)o;
        }else{
            User user= userDao.selectUserWithId(id);
            if(user!=null){
                redisTemplate.opsForValue().set("user_"+id,user,1000, TimeUnit.SECONDS);
            }
            return user;
        }
    }

    @Override
    public User getByUserName(String username) {
        log.info("username:"+username);
//        Object o=redisTemplate.opsForValue().get("user_"+username);
        Object o=null;
        if(o!=null){
            return (User)o;
        }else{
            User user= userDao.getUserByName(username);
            log.info("user:"+user);
            if(user!=null){
                redisTemplate.opsForValue().set("user_"+username,user,1000, TimeUnit.SECONDS);
            }
            return user;
        }
    }

    @Override
    public List<Authority> getAuthority(String username) {
        return null;
    }

    @Override
    public List<User> getAllUser() {
        return userDao.getAllUser();
    }

    @Override
    public Integer addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public Integer addAuthorityByUser(Integer userId, Integer authorityId) {
        return userDao.addAuthorityByUser(userId,authorityId);
    }

    @Override
    public Integer update(User user) {
        return userDao.update(user);
    }

}
